/**
 * 
 */
package com.demo2do.boyle.backend.service.system.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.boyle.backend.cache.accessor.PersistentAccessor;
import com.demo2do.boyle.backend.service.system.GeoService;
import com.demo2do.boyle.common.entity.geo.Geo;
import com.demo2do.boyle.common.entity.system.tag.Tag;
import com.demo2do.boyle.common.entity.system.tag.Type;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.support.Filter;
import com.demo2do.core.service.impl.GenericServiceImpl;
import com.demo2do.core.web.resolver.Page;

/**
 * @author Leo mohanlan
 *
 */
@Service("geoService")
public class GeoServiceImpl extends GenericServiceImpl<Geo> implements GeoService {

	@Autowired 
	private GenericDaoSupport genericDaoSupport;
	
	@Autowired
	private PersistentAccessor persistentAccessor;
	
	/* (non-Javadoc)
	 * @see com.demo2do.boyle.backend.service.system.GeoService#listGeos()
	 */
	@SuppressWarnings("unchecked")
	public List<Geo> listGeos() {
		return genericDaoSupport.searchForList("FROM Geo geo WHERE geo.active = true ORDER BY  geo.hot DESC, geo.level ASC");
	}

	/* (non-Javadoc)
	 * @see com.demo2do.boyle.backend.service.system.GeoService#search(java.lang.String, java.lang.Boolean)
	 */
	@SuppressWarnings("unchecked")
	public List<Geo> search(String name, Boolean hot, Page page) {
		
		Filter filter = new Filter().addLike("name", name)
									.addEquals("hot", hot)
									.addEquals("active", false);
		
		String querySentence = "FROM Geo geo";
		
		List<Geo> result = genericDaoSupport.searchForList(querySentence + filter.getWhereSentence() , filter.getParameters(), page.getBeginIndex(), page.getMaxResultRecords());
				
		return result.size() > page.getEveryPage() ? result.subList(0, page.getEveryPage()) : result;
	}

	/* (non-Javadoc)
	 * @see com.demo2do.boyle.backend.service.system.GeoService#activate(java.lang.String[])
	 */
	public void activate(String[] codes) {
		
		// 1. change status of geos
		genericDaoSupport.executeHQL("UPDATE Geo SET active = true WHERE code in ( :codes )", "codes", codes);
		
		int length =(int) persistentAccessor.getAreaTags().size();
		
		// 2. get the largest area code
		int currentTagCode = (int) Math.pow(2, length-1);
		
		for(int i = 0; i < codes.length; i++) {
			
			currentTagCode = currentTagCode * 2;
		
			Geo geo = genericDaoSupport.load(Geo.class, codes[i]);
			
			Tag tag = new Tag(currentTagCode, geo.getName(), Type.GEO, Integer.parseInt(geo.getCode()));
			
			genericDaoSupport.save(tag.initialize());

		}
	}
	
}
